'use strict';
const Service = require('egg').Service;
const path = require('path');
const fs = require('fs/promises');
class GenerateRouteService extends Service {
  async run() {
    const { cw } = this.ctx.helper;
    const rl = await this.ctx.model.CwMenu.findAll({
      include: [{ model: this.ctx.model.CwMenuMod }],
      order: [[ 'sort', 'ASC' ]],
      where: { admin: true },
    });
    // console.log(JSON.stringify(rl, null, 2));
    let item = '';
    for (const v of rl) {
      const middleware = `${v.cw_menu_mod.middleware},${v.middleware}`;
      const ignoreMiddleware = v.ignoreMiddleware.split(',');
      // console.log(middleware.split(','));
      // console.log([ ...ignoreMiddleware, '' ]);
      const mw = cw._.difference(middleware.split(','), [ ...ignoreMiddleware, '' ]);
      // console.log(cw._.uniq(mw));
      const marr = [];
      for (const m of cw._.uniq(mw)) {
        marr.push(`app.middleware.${m}()`);
      }
      // console.log(marr.join(','));
      const mstr = cw._.isEmpty(marr.join(', ')) ? ', ' : `, ${marr.join(' ,')}, `;
      let controller;
      if (v.verb === 'resources') {
        controller = `'${v.controller}'`;
      } else if (v.verb === 'redirect') {
        controller = 302;
      } else {
        controller = `'${v.controller}.${v.action}'`;
      }
      item += `  app.router.${v.verb}('${v.name}', '${v.path}'${mstr}${controller});
`;
    }
    const routerData = `'use strict';
module.exports = app => {
${item}
};
`;
    const appDir = path.join(this.app.baseDir, 'app', 'router');
    const fileName = 'webRouter.js';
    const file = path.join(appDir, fileName);
    try {
      const data = new Uint8Array(Buffer.from(routerData));
      await fs.writeFile(file, data);
      // Abort the request before the promise settles.
    } catch (err) {
      // When a request is aborted - err is an AbortError
      console.error(err);
    }
  }
}
module.exports = GenerateRouteService;
